import subprocess
import shlex
import ssl
from pymisp import ExpandedPyMISP
from threading import Timer


class Tools:
    @staticmethod
    def run_cmd(cmd, timeout=15, shell=False):
        outs, errs = None, None
        proc = subprocess.Popen(shlex.split(cmd),
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True,
                                shell=shell)
        timer = Timer(timeout, lambda process: process.kill(), [proc])
        try:
            timer.start()
            outs, errs = proc.communicate()
            return outs, errs
        finally:
            timer.cancel()

    @staticmethod
    def md5sum(file_path):
        result = None
        result = Tools.run_cmd('md5sum {}'.format(file_path), timeout=1200)
        if result is not None:
            result = result[0].split()[0]
        return result

    @staticmethod
    def sha256sum(file_path):
        result = None
        result = Tools.run_cmd('sha256sum {}'.format(file_path), timeout=1200)
        if result is not None:
            result = result[0].split()[0]
        return result

    @staticmethod
    def init_misp(url, key):
        ssl._create_default_https_context = ssl._create_unverified_context
        return ExpandedPyMISP(url, key, ssl=False)
